from settings import *
import pickle
import simplejson as sj
import urllib
import urllib2
import random
rand = random.SystemRandom()


url = 'http://localhost:8080/'
rsa = pickle.loads(RSA_KEY)
dsa = pickle.loads(DSA_KEY)

def generate_auth_key(key):
    return rsa.encrypt(key,'')[0].encode('base64')
def get_dsa_pub():
    return sj.dumps(dsa.publickey().__getstate__())

def getrandlong(dsa):
    return long(rand.randrange(2,dsa.q))

def generate_dsa_key(key):
    def f():
        return sj.dumps(dsa.sign(key,getrandlong(dsa)))
    return f
def authenticate(clientname):
    encode = urllib.urlencode
    urlopen = urllib2.urlopen
    data = {}
    data['clientname'] = clientname
    key = urlopen(url,encode(data)).read()
    
    if key.startswith('Error:'):
        return (-1,key)

    data['clientaction'] = 'verify_key'
    data['key'] = generate_auth_key(key)
    data['dsapub'] = get_dsa_pub()
    key = urlopen(url,encode(data)).read()
    if key.startswith('Error:'):
        return (-2,key)
    d = {'clientname':clientname,
         'clientaction':'verify_session',
         'keyfunc':generate_dsa_key(key)
        }
    return d

def listcommands():
    return urllib2.urlopen(url).read()
def callfunc(d,command,args):
    urlopen = urllib2.urlopen
    encode = urllib.urlencode
    c = d.copy()
    c['key'] = c['keyfunc']()
    del c['keyfunc']

    newurl = '%s%s/'%(url,command)

    c['args'] = sj.dumps(args)
    
    return sj.loads(urlopen(newurl,encode(c)).read())
    
    

        



    
